package com.dts.evaluate.ui.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dts.evaluate.R;
import com.dts.evaluate.bean.PersonBroadBean;
import com.dts.evaluate.bean.Worker;
import com.dts.evaluate.common.Constants;
import com.dts.evaluate.common.SocketType;
import com.dts.evaluate.controller.impl.DataImpl;
import com.dts.evaluate.controller.intf.DataInterface;
import com.dts.evaluate.ui.view.MarqueTextView;
import com.dts.evaluate.ui.view.TitleView;
import com.dts.evaluate.utils.ApkUtil;
import com.dts.evaluate.utils.BitmapUtils;
import com.dts.evaluate.utils.IdUtil;
import com.dts.evaluate.utils.JSONUtils;
import com.dts.evaluate.utils.LogUtil;
import com.dts.evaluate.utils.PreferencesUtils;
import com.dts.evaluate.utils.SocketUtil;
import com.dts.evaluate.utils.StringUtils;
import com.dts.evaluate.utils.ToastUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends BaseActivity implements TitleView.OnBackClikListener, View.OnClickListener {

    @Bind(R.id.title_view)
    TitleView titleView;
    @Bind(R.id.name_textview)
    TextView nameTextview;
    @Bind(R.id.organ_textview)
    TextView organTextview;
    @Bind(R.id.position_textview)
    TextView positionTextview;
    @Bind(R.id.work_number_textview)
    TextView workNumberTextview;
    @Bind(R.id.device_id_textview)
    TextView deviceIdTextview;
    @Bind(R.id.marque_textview)
    MarqueTextView marqueTextview;
    @Bind(R.id.hide_layout)
    LinearLayout hideLayout;
    @Bind(R.id.banner_imageview)
    ImageView bannerImageview;
    @Bind(R.id.responsiblity_layout)
    LinearLayout responsiblityLayout;
    @Bind(R.id.kbsx_layout)
    LinearLayout kbsxLayout;
    @Bind(R.id.depart_broad_layout)
    LinearLayout departBroadLayout;
    @Bind(R.id.net_layout)
    LinearLayout netLayout;
    @Bind(R.id.person_pic_imageview)
    ImageView personPicImageview;
    @Bind(R.id.tv)
    TextView tv;

    private LayoutInflater mInflater;
    private AlertDialog mDialog;//个人公告输入密码对话框

    private Worker mWorker;
    private InitDataBoradcastReciever reciever;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        //初始化inflater
        mInflater = LayoutInflater.from(this);

        //初始化控件
        initView();

        //注册启动后绑定，服务器返回数据刷新界面广播
        reciever = new InitDataBoradcastReciever();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SocketType.CALL_BACK_INIT_MSG);
        intentFilter.addAction(SocketType.CALL_BACK_PERSON_BROAD);
        registerReceiver(reciever, intentFilter);

        ApkUtil.installNewApk(this);

        //加载banner
        loadBanner();
        LogUtil.v("oncreate:");

        //初始化socket连接
        SocketUtil.init(this);

    }

    private void initView() {
        //设置titleview个人公告点击监听
        titleView.setOnBackClickListener(this);
        hideLayout.setOnClickListener(this);

        //设置其他控件点击监听
        responsiblityLayout.setOnClickListener(this);
        kbsxLayout.setOnClickListener(this);
        departBroadLayout.setOnClickListener(this);
        netLayout.setOnClickListener(this);

        deviceIdTextview.setText(IdUtil.getDeviceId(this));

    }

    @Override
    public void onTitleViewClik(View v) {
        //显示输入密码进入个人公告对话框
        if (mWorker == null) {
            ToastUtils.show(this, R.string.please_bind_when_use);
            return;
        }

        showInputPasswordDialog();
    }

    /**
     * 显示输入密码进入个人公告对话框
     */
    private void showInputPasswordDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.person_cast);

        View v = mInflater.inflate(R.layout.dialog_input_password_layout, null);
        final EditText passwordEdittext = (EditText) v.findViewById(R.id.password_edittext);
        TextView sureTextView = (TextView) v.findViewById(R.id.sure_textview);
        TextView cancelTextView = (TextView) v.findViewById(R.id.cancel_textview);

        builder.setView(v);

        sureTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String password = passwordEdittext.getText().toString();
                if (StringUtils.isBlank(password)) {
                    passwordEdittext.setError(getResources().getString(R.string.password_cant_null));
                    return;
                }

                checkWorkerPassword(password);

            }
        });
        cancelTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });

        mDialog = builder.create();
        mDialog.show();
    }

    public static final int PERSON_BROAD_CODE = 1;

    /**
     * 请求服务器查看密码
     *
     * @param password
     */
    private void checkWorkerPassword(final String password) {
        showProgress();
        DataInterface dataInterface = new DataImpl();
        dataInterface.checkPassoword(Constants.CHECK_PASSWORD_URL, String.valueOf(mWorker.getTableIdOfGscUser()), new StringCallback() {
            @Override
            public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                super.onError(isFromCache, call, response, e);
                hideProgress();
                showErrorDialog("", getResources().getString(R.string.dialog_net_error));
            }

            @Override
            public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                hideProgress();

                //解析json得到password
                String netPassword = JSONUtils.getString(s, Constants.PASSWORD, "");

                if (StringUtils.isEquals(password, netPassword)) {
                    //关闭输入法
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

                    //关闭对话框
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }

                    //将密码存放本地
                    PreferencesUtils.putString(MainActivity.this, Constants.PASSWORD, password);

                    //启动个人公告界面
                    Intent intent = new Intent(MainActivity.this, PersonBroadActivity.class);
                    intent.putExtra(Constants.WORKER, mWorker);
                    startActivityForResult(intent, PERSON_BROAD_CODE);
                } else {
                    showErrorDialog("", getResources().getString(R.string.password_error));
                }
            }
        }, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {

            boolean isRecovery = data.getBooleanExtra(Constants.IS_RECOVERY, false);

            //从主界面取消个人公告
            if (isRecovery) {
                marqueTextview.setText("");
                hideLayout.setVisibility(View.GONE);
                return;
            }

            //发布个人公告到主界面
            PersonBroadBean personBroadBean = (PersonBroadBean) data.getSerializableExtra(Constants.PERSON_BROAD_BEAN);
            initPersonBroad(personBroadBean);

        }

    }


    @Override
    public void onClick(View v) {
        //绑定后使用
        if (mWorker == null) {
            ToastUtils.show(this, R.string.please_bind_when_use);
            return;
        }
        Intent intent = null;
        switch (v.getId()) {
            case R.id.responsiblity_layout:
                intent = new Intent(this, ResponsibiliesActivity.class);
                intent.putExtra(Constants.WORKER, mWorker);
                startActivity(intent);
                break;
            case R.id.kbsx_layout:
                intent = new Intent(this, KbsxActivity.class);
                intent.putExtra(Constants.WORKER, mWorker);
                startActivity(intent);
                break;
            case R.id.depart_broad_layout:
                intent = new Intent(this, DepartBroadActivity.class);
                intent.putExtra(Constants.WORKER, mWorker);
                startActivity(intent);
                break;
            case R.id.net_layout:
                intent = new Intent(this, GoverNetActivity.class);
                startActivity(intent);
                break;
            //点击hideLayou的监听
            case R.id.hide_layout:
                showInputPasswordDialog();
                break;
        }

    }

    /**
     * 加载banner
     */
    private void loadBanner() {
        LogUtil.v("loadBanner  function"+System.currentTimeMillis());
        DataInterface dataInterface = new DataImpl();
        dataInterface.getBanner(Constants.KBSX_URL, Constants.TYPE_BANNER, "", new StringCallback() {
            @Override
            public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                if(StringUtils.isBlank(s)){
                    return;
                }
                try {
                    JSONArray jsonArray = JSONUtils.getJSONArray(new JSONObject(s),"IssueBulletin",null);
                    if(jsonArray == null || jsonArray.length() == 0){
                        return;
                    }
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    String base64 = JSONUtils.getString(jsonObject,"filedata","");
                    Bitmap bitmap = BitmapUtils.base64ToBitmap(base64);
                    if(bitmap != null){
                        bannerImageview.setImageBitmap(bitmap);
                    }

                    LogUtil.v("bm:"+bitmap);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销广播
        unregisterReceiver(reciever);
        //清楚个人公告本地储存数据
        PreferencesUtils.putString(this, Constants.PERSON_BROAD_BEAN, "");
        //断开soket连接
        SocketUtil.disConnect();
    }

    /**
     * 接受注册绑定后的广播，用于刷新界面工作人员信息
     */
    public class InitDataBoradcastReciever extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //初始化人员信息
            if (SocketType.CALL_BACK_INIT_MSG.equals(action)) {
                Worker worker = (Worker) intent.getSerializableExtra(SocketType.CALL_BACK_INIT_MSG);
                mWorker = worker;
                //初始化人员信息
                initWorkerInfo(worker);
            }
            //初始化个人公告信息
            if (SocketType.CALL_BACK_PERSON_BROAD.equals(action)) {
                PersonBroadBean personBroadBean = (PersonBroadBean) intent.getSerializableExtra(Constants.PERSON_BROAD_BEAN);
                initPersonBroad(personBroadBean);
            }
        }
    }

    /**
     * 初始化人员信息
     *
     * @param worker
     */
    private void initWorkerInfo(Worker worker) {
        if (worker != null) {
            String userName = worker.getGscUserName();
            String organName = worker.getGscOrganName();
            String jobType = worker.getGscUserJobTypeCodeId();
            String userLogo = worker.getUserLogo();
            String duty = worker.getGscUserPoliticalDuty();
            String workId = worker.getGscWorkCardNum();

            nameTextview.setText("" + userName);
            organTextview.setText("" + organName);
            positionTextview.setText("" + duty);
            workNumberTextview.setText("" + workId);
            if (!StringUtils.isEmpty(userLogo)) {
                //处理服务端过来的  非人base64数据
                userLogo = userLogo.substring(userLogo.indexOf("base64,"), userLogo.length()).replace("base64,", "");
                Bitmap bm = BitmapUtils.base64ToBitmap(userLogo);
                if (bm != null) {
                    personPicImageview.setImageBitmap(bm);
                }
            }
        }
    }

    /**
     * 初始化个人公告信息
     *
     * @param personBroadBean
     */
    private void initPersonBroad(PersonBroadBean personBroadBean) {
        if (personBroadBean == null) {
            return;
        }
        String beginTime = personBroadBean.getTxtbegintime();
        String endTime = personBroadBean.getTxtendtime();
        String reason = personBroadBean.getTxtreason();
        String tel = personBroadBean.getTxttel();
        int act = personBroadBean.getAction();
        boolean isPcBroad = personBroadBean.isPcBroad();

        if (act == Constants.BROAD_ON) {
            hideLayout.setVisibility(View.VISIBLE);
            marqueTextview.setText("                    个人公告：" + reason + "        联系电话：" + tel + "          时间：" + beginTime + " 至 " + endTime);
        } else if (act == Constants.BROAD_OFF) {
            hideLayout.setVisibility(View.GONE);
            marqueTextview.setText("");
        }

        //如果是pc端发布的个人公告，则不可点击并且清楚平板储存的个人公告
        if (isPcBroad) {
            hideLayout.setOnClickListener(null);
            PreferencesUtils.putString(this, Constants.PERSON_BROAD_BEAN, "");
        } else {
            hideLayout.setOnClickListener(this);
        }

    }

    private float width = 100;
    private int count;
    private boolean isCount = false;
    private RectF rectF = new RectF(0, 0, width, width);
    private Timer timer;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            float x = ev.getX();
            float y = ev.getY();
            if (rectF.contains(x, y)) {
                LogUtil.v("count:" + count);
                if (!isCount) {
                    isCount = true;
                    if (timer != null) {
                        try {
                            timer.cancel();
                            timer = null;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            if (count >= 4) {
                                finish();
                            }
                            count = 0;
                            isCount = false;
                        }
                    }, 2 * 1000);
                }
                count++;

            }

        }
        return super.dispatchTouchEvent(ev);
    }

}
